<?php

// $Id$


require_once(TANGRA_MAIN_DIR.'db/paginate_db_data.class.php');
require_once(TANGRA_MAIN_DIR.'grids/grid_ctrl.class.php');

require_once('cis_grid.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_type_dbc.class.php');


class CIs_Grid_Ctrl extends Grid_Ctrl {
	private $hidden_inc_dir;

	function __construct($system_name, Vars_Manager $vm, $method = Tangra_Parameter_Method::GET, $hidden_inc_dir) {
		parent::__construct($system_name, $vm, $method);
		$this->hidden_inc_dir = $hidden_inc_dir;
	}


	protected function create_grid() {
		$ret = new CIs_Grid();
		$this->set_user_defined_post_processing_method('postprocessing');
		return $ret;
	}


	protected function postprocessing(DB_Connection $dbc, $rows) {
		foreach($rows as $key => &$row) {
			$type = new TCMS_CI_Type_DBC();
			if (!$type->load_by_id($dbc, $row[2])) {
				throw new Tangra_Module_Exception('Cannot load content type with id = '.$row[3]);
			}

			$row[3] = $type->get_name();
			$row[4] = $this->prepare_content($dbc, $type, $this->hidden_inc_dir, $row[0]);
			$row[5] = $type->get_page_manage_path();
			$row[6] = $type->get_page_delete_path();
			$row[7] = $type->get_page_preview_path();

		}

		return $rows;
	}


	protected function create_paginate_db_data() {

		$sqls = '';
		$sqlc = '';

		$pdbd = new Paginate_DB_Data($this->grid->get_page_size(), $sqls, $sqlc);

		return $pdbd;
	}



	public function process(DB_Connection $dbc, $page = NULL) {
		$vm = $this->get_vm();

		$sql = $this->get_sqls($vm);

		$this->paginate_db_data->set_sql_select($sql['sqls']);
		$this->paginate_db_data->set_sql_count($sql['sqlc']);

		parent::process($dbc, $page);
	}


	private function get_sqls($vm) {
		$text = $vm->get_page_var('ci', 'text');
		$id = $vm->get_page_var('ci', 'id');

		$sqls = TCMS_CI_DBC::get_sql_for_grid($text, $id);
		$sqlc = TCMS_CI_DBC::get_sql_count_for_grid($text, $id);

		$sql['sqls'] = $sqls;
		$sql['sqlc'] = $sqlc;

		return $sql;
	}



	private function prepare_content(DB_Connection $dbc, TCMS_CI_Type_DBC $type, $hidden_inc_dir, $ci_id) {
		$class_name = $type->get_class_name();
		if (!class_exists($class_name)) {
			require_once($hidden_inc_dir.$type->get_class_path());
		}

		$ci = new $class_name;
		$ci->load_by_id($dbc, $ci_id);

		return $ci->get_as_short_plain_text();
	}
}